package cn.zy.company.servlet.admin;

import cn.zy.company.entity.News;
import cn.zy.company.entity.PageObj;
import cn.zy.company.entity.User;
import cn.zy.company.service.NewsService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;


@WebServlet("/admin/editNews")
public class EditNewsServlet extends HttpServlet {
    NewsService newsService = new NewsService();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            String id = req.getParameter("id");
            if (id != null && id != "") {
                PageObj<News> pageObj = newsService.findById(Integer.valueOf(id));
                List<News> list = pageObj.getList();
                for (News news : list) {
                    req.setAttribute("data", news);
                    req.getRequestDispatcher("/WEB-INF/jsp/admin/editNews.jsp").forward(req, resp);
                    return;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            Integer id = Integer.valueOf(req.getParameter("id"));
            System.out.println(id);
            String name = req.getParameter("name");
            String value = req.getParameter("value");
            User loginUser = (User) req.getSession().getAttribute("loginUser");
            Integer userId = loginUser.getId();
            News news = new News(name, value, userId, null);
            news.setId(id);
            news.setDate(new Date());
            newsService.update(news);
            resp.sendRedirect("showNews");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
